<template>
    <rx-layout>
        <div slot="left" width="200" showButton="true">
            <rx-fit>
                <rx-category-treeeditor
                    cat-key="FORM"
                    :statisticConfig="statisticConfig"
                    :edit="true"
                    @handSelect="handSelect"
                    :async="true"
                    v-if="isShowManageTree"
                    :isAdmin="isManageToTree"
                    :checkToDel="true"
                ></rx-category-treeeditor>
            </rx-fit>
        </div>
        <div slot="center" style>
            <rx-fit :isheader="isheader">
                <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
                    <div class="table-operator">
                        <a-button type="primary" icon="plus" v-if="findAuthRight('add')" @click="add">
                            {{$ti18('rxList.newBtn','新建')}}
                        </a-button>
                        <a-button type="primary" v-if="!isAppDevelop && selectedRowKeys.length > 0 " icon="redo"
                                  @click="changeApp('FORM',selectedRows,'pkId','name','appId','treeId',changeAppId)">
                            {{i18n('list.ChangeApplication','变更应用')}}

                        </a-button>
                        <a-button v-if="selectedRowKeys.length > 0"
                                  type="primary"
                                  icon="switcher" @click="openCategoryDialog">
                            {{$ti18('rxList.changeCategory','切换分类')}}
                        </a-button>
                        <a-dropdown v-if="selectedRowKeys.length > 0 && ((removeEnable && findAuthRight('delete')) || (editEnable && findAuthRight('edit')))">
                            <a-button style="margin-left: 8px">
                                {{$ti18('rxList.moreBtn','更多')}}
                                <a-icon type="down"/>
                            </a-button>
                            <a-menu slot="overlay">
                                <a-menu-item key="1" @click="editOne1" v-if="editEnable && findAuthRight('edit')"
                                             :butn-type="'primary'" :show-no-right="false">
                                    <a-icon type="edit"/>
                                    {{$ti18('rxList.editBtn','编辑')}}
                                </a-menu-item>
                                <a-menu-item key="1" @click="delByRowKeys(selectedRowKeys)"
                                             v-if="removeEnable && findAuthRight('delete')" alias="formRuleDelete"
                                             :butn-type="'danger'"
                                             :show-no-right="false">
                                    <a-icon type="delete"/>
                                    {{$ti18('rxList.delBtn','删除')}}
                                </a-menu-item>
                                <a-menu-item
                                    key="2"
                                    @click="changeExport(exportConf)"
                                    v-if="selectedRowKeys.length > 0"
                                    alias="formRuleDelete"
                                    :butn-type="'primary'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="switcher"/>
                                    {{$ti18('rxList.changeExport','切换导出')}}
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </div>
                    <span class="search-btn-box" v-if="!isheader">
                <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>
                    {{$ti18('rxList.leachBtn','过滤')}}
                </span>
          </span>
                </div>
                <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
                     @close="closeSearchbar">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.name','名称')">
                                    <a-input :placeholder="i18n('form.name','名称','input')" v-model="queryParam.Q_NAME__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.alias','别名')">
                                    <a-input :placeholder="i18n('form.alias','别名','input')" v-model="queryParam.Q_ALIAS__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan" v-if="!curApp.appId">
                                <a-form-item :label="$ti18('rxForm.appId', '应用')">
                                    <rx-search-app @change="appChange" v-model="searchApps">
                                    </rx-search-app>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan" v-if="isheader">
                    <span class="table-page-search-submitButtons">
                      <a-button type="primary" icon="search" @click="search">
                         {{$ti18('rxList.searchBtn','查询')}}
                      </a-button>
                      <a-button style="margin-left: 4px" @click="cancel">
                          {{$ti18('rxList.resetBtn','重置')}}
                      </a-button>
                      <a @click="toggleAdvanced" style="margin-left: 8px">
                        {{ advanced ? $ti18('rxList.putAwayBtn','收起') : $ti18('rxList.openBtn','展开') }}
                        <a-icon :type="advanced ? 'up' : 'down'"/>
                      </a>
                    </span>
                            </a-col>
                            <template v-if="advanced">
                                <a-col :span="colSpan">
                                    <a-form-item :label="i18n('form.tableName','表名')">
                                        <a-input :placeholder="i18n('form.tableName','表名','input')" v-model="queryParam.Q_TABLE_NAME__S_LK"/>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="colSpan">
                                    <a-form-item :label="i18n('list.isGenTable','是否生成物理表')">
                                        <a-select allowClear v-model="queryParam.Q_GENDB__S_LK">
                                            <a-select-option key="1">{{i18n('gendbMap.generated','已生成')}}</a-select-option>
                                            <a-select-option key="0">{{i18n('gendbMap.NotGenerated','未生成')}}</a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                            </template>
                        </a-row>
                    </a-form>
                </div>
                <rx-grid
                    ref="table"
                    :bordered="isBorder"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :columns="columns"
                    :defaultPageSize="10"
                    url="/api-form/form/bo/formBoEntity/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="['10','30','40']"
                    id-field="id"
                    :loadDataOnstart="true"
                    @selectChange="onSelectChange"
                >
                    <span slot="exportApp">
                         {{ exportI18n('export.isExport','导出') }}
                        <export-app/>
                    </span>
                    <span slot="genMode" slot-scope="{text,record}">
                        <a-tag :color="genModeMap[text].color">
                            <span>{{genModeMap[text].text}}</span>
                        </a-tag>
                    </span>
                    <span slot="gendb" slot-scope="{text,record}">
                        <a-tag :color="gendbMap[text].color">
                            <span>{{gendbMap[text].text}}</span>
                        </a-tag>
                    </span>
                    <span slot="appId" slot-scope="{ text, record }">
                        {{allApps[text]? $i18(allApps[text].appName,'应用名称') : $ti18('rxList.noAppName','无')}}
                    </span>
                    <span slot="isExport" slot-scope="{ text, record }">
                        <a-tag :color="text == 1 ? 'green' : 'red'">
                            <span>{{ text == 1 ? exportI18n('export.yes','是') : exportI18n('export.no','否') }}</span>
                        </a-tag>
                    </span>
                    <span slot="action" slot-scope="{text, record}" class="actionIcons" size="2">
                        <span @click.stop="edit(record)">
                            {{$ti18('rxList.editBtn','编辑')}}
                        </span>
                        <span v-if="record.gendb==1" @click.stop="indexManager(record)" :title="i18n('list.indexManag','索引管理')">
                            {{i18n('list.indexManag','索引管理')}}
                        </span>
                        <span v-if="findAuthRight('delete') && removeEnable" @click.stop="delByIds([record.id],record.gendb)">
                            {{$ti18('rxList.delBtn','删除')}}
                        </span>
                        <span v-if="record.gendb==1" @click.stop="unboundTable(record)" :title="i18n('list.unbindTable','解绑物理表')">
                            {{i18n('list.unbindTable','解绑物理表')}}
                        </span>
                        <span v-if="record.gendb==1" @click.stop="deleteBoTable(record)">
                            {{i18n('list.delTable','删除物理表')}}
                        </span>
                        <span v-else @click.stop="createBoTable([record.id])">
                            {{i18n('list.genTable','生成物理表')}}
                        </span>
                        <span @click="setExport(record,exportConf)">{{record.isExport == 1 ? exportI18n('export.noExport','不导出') : exportI18n('export.exported','导出')}}</span>
                    </span>
                </rx-grid>
                <a-modal
                    :title="$ti18('rxMsa.delInfo','确定需要删除选中的记录吗？')"
                    style="top: 100px;"
                    :width="400"
                    v-model="visible"
                    :confirmLoading="confirmLoading"
                    @ok="handleOk"
                >
                    <a-checkbox v-model="delTable">
                        {{i18n('list.isDelTable','是否删除物理表')}}
                    </a-checkbox>
                </a-modal>
            </rx-fit>
        </div>
    </rx-layout>
</template>

<script>
import FormBoEntityApi from '@/api/form/bo/formBoEntity'
import FormBoEntityEdit from './FormBoEntityEdit'
import {BaseList,Util} from "@lowcode/jpaas-common-lib";
import RxCategoryTreeeditor from "@/components/redxun/rx-category-treeeditor";
import changeAppJs from "@/views/modules/share/changeApp";
import IndexComponent from "./indexManager/indexComponent.vue";
import { mapState} from 'vuex';
import exportApp from "@/views/modules/share/exportApp";
import SysAppApi from "@/api/system/core/sysApp";
import AppSearch from "@/views/modules/share/AppSearch";
import RxSearchApp from "@/views/modules/share/rx-search-app";
import switchExport from "@/utils/switchExport";
import ChangeCategory from "@/views/modules/share/ChangeCategory";
import FormBoDefApi from "@/api/form/bo/formBoDef";

export default {
    name: 'FormBoEntityList',
    mixins: [BaseList,changeAppJs,AppSearch,switchExport,ChangeCategory],
    components: {
        FormBoEntityEdit,
        RxCategoryTreeeditor,
        IndexComponent,
        exportApp,
        RxSearchApp
    },
    computed: {
        ...mapState({
            // 所属应用
            allApps: state => state.appSetting ? state.appSetting.allApps : {}
        }),
    },
    filters: {},
    data() {
        return {
            columns: [
                {
                    title: this.$ti18('rxList.index','序号'),
                    type: 'indexColumn',
                    width: 60,
                    dataIndex: 'serial',
                    scopedSlots: {customRender: 'serial'}
                },
                {title: this.i18n('form.name','名称'), sorter:true,sortField:'NAME_',dataIndex: 'name',width: 120 },
                {title: this.i18n('form.alias','别名'), dataIndex: 'alias', sorter:true,sortField:'ALIAS_', width: 120},
                {title: this.i18n('form.genMode','创建方式'), dataIndex: 'genMode', sorter:true,sortField:'GEN_MODE_',width: 140, scopedSlots: {customRender: 'genMode'}},
                {title: this.i18n('form.tableName','表名'), dataIndex: 'tableName',sorter:true,sortField:'TABLE_NAME_', width: 120},
                {title: this.i18n('form.gendb','生成库'), dataIndex: 'gendb', width: 140,sorter:true,sortField:'GENDB_', scopedSlots: {customRender: 'gendb'}},
                {title: this.i18n('form.app','所属应用'), dataIndex: 'appId', width: 100, sortField: 'APP_ID_',scopedSlots: {customRender: 'appId'}},
                {
                    dataIndex: 'isExport',
                    slots: { title: 'exportApp' },
                    width: 100,
                    scopedSlots: {customRender: 'isExport'}
                },
                {title: this.$ti18('rxForm.createTime','创建时间'), dataIndex: 'createTime',  width: 130},
                {title: this.$ti18('rxList.action','操作'), dataIndex: 'action',fixed: 'right', scopedSlots: {customRender: 'action'}, width: 150}
            ],
            component: FormBoEntityEdit,
            comment: this.i18n('list.comment','业务实体'),
            gendbMap: {
                1: {color: 'green', text: this.i18n('gendbMap.generated','已生成')},
                0: {color: 'red', text: this.i18n('gendbMap.NotGenerated','未生成')},
            },
            genModeMap: {
                'form': {color: 'green', text: this.i18n('genModeMap.form','表单')},
                'create': {color: 'red', text: this.i18n('genModeMap.design','设计')},
                'db': {color: 'orange', text: this.i18n('genModeMap.dbReflect','库表反射')},
                'easyform': {color: 'gold', text: this.i18n('genModeMap.easyForm','拖拽表单')},
                'dragform': {color: 'gold', text: this.i18n('genModeMap.easyForm','拖拽表单')}
            },
            visible:false,
            confirmLoading:false,
            delTable:false,
            curTree:{},
            statisticConfig: {
                type:"static_form",
                table:"FORM_BO_ENTITY",
                field:"TREE_ID_",
                whereConf: []
            },
            /**
             * 导出配置
             */
            exportConf:{
                Api:FormBoEntityApi,
                id:"id"
            },
            //变更分类配置
            categoryConfig:{
                Api:FormBoEntityApi,
                catKey:"FORM",
                gridRef:"table"
            }
        }
    },
    created() {
        this.isUserManager(this.$route.query.appId);
        this.needFilterAppId("isAppMenu");
        this.columns=this.removeAppColumn(this.curApp.appId,this.columns)
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formBoEntity",key);
        },
        exportI18n(name,text,key){
            return this.$ti18(name,text,"appExport",key);
        },
        delByIds(ids,gendb) {
            this.selectedRowKeys = ids;
            if(gendb==1) {
                this.visible = true;
            }else{
                let self_ = this;
                this.$confirm({
                    title: this.$ti18('rxMsa.actionTips','操作提示'),
                    zIndex: 20000,
                    content: this.$ti18('rxMsa.delInfo','您确定需要删除选中的记录吗?'),
                    okText: this.$ti18('rxForm.ackBtn','确认'),
                    cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                    onOk() {
                        self_.handleOk();
                    },
                    onCancel() {
                    }
                })
            }
        },
        editOne1() {
            var conf = {
                component: this.component,
                title: this.$ti18('rxList.editBtn','编辑')+"-" + this.comment,
                urlType: 'Edit',
                widthHeight: this.widthHeight
            };
            if (this.selectedRows.length > 0) {
                if (this.selectedRows.length > 1) {
                    alert(this.$ti18('rxMsa.editRecordsWarn','选中多条记录时不能编辑!'),);
                    return;
                }
                if(this.selectedRows[0].genMode=='form'){
                    alert(this.i18n('msg.noEdit','创建方式为表单生成时不能编辑!'));
                    return;
                }
                conf.pkId = this.selectedRows[0].pkId;
                this.handleEdit(conf)
            }
        },
        handleOk() {
            var self = this;
            this.confirmLoading = true;
            FormBoEntityApi.del({ids: this.selectedRowKeys.join(','),delTable:this.delTable}).then(res => {
                    this.confirmLoading = false;
                    this.visible = false;
                    this.delTable = false;
                    var type = "success";
                    if (!res.success) {
                        type = "error";
                    } else {
                        self.$refs.table.loadData();
                    }
                    self.$notification[type]({
                        message: this.$ti18('rxMsa.actionTips','操作提示'),
                        description: res.message,
                        duration: 1.5
                    });
                }
            );
        },
        delByRowKeys(selectedRowKeys) {
            var ids = [];
            var gendb=false;
            for (var i = 0; i < this.selectedRows.length; i++) {
                if(this.selectedRows[i].gendb==1){
                    gendb=true;
                }
                ids.push(this.selectedRows[i].id);
            }
            this.delByIds(ids,gendb);
        },
        getListByParams(parameter) {
            return FormBoEntityApi.query(parameter)
        },
        deleteBoTable(record) {
            var self = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.i18n('msg.delTableMsg','该操作会删除实体关联的表,确定清除物理表吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    FormBoEntityApi.deleteBoTable(record.id, record.tableName).then(res => {
                        self.refreshGrid();
                    })
                }
            })
        },
        unboundTable(record) {
            var self = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.i18n('msg.unBindTabMsg','该操作会解绑实体关联的表,确定解绑吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    FormBoEntityApi.unboundTable(record.id).then(res => {
                        self.refreshGrid();
                    })
                }
            })
        },
        createBoTable(id) {
            var self = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.i18n('msg.genTableMsg','该操作会生成实体关联的表,确定生成物理表吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    FormBoEntityApi.creatBoTable(id).then(res => {
                        self.refreshGrid();
                    })
                }
            })
        },
        handSelect(curRow) {
            this.curTree=curRow;
            var treeId = curRow.treeId;
            if(treeId!="0"){
                this.queryParam.Q_TREE_ID__S_EQ=treeId;
            }else {
                delete this.queryParam.Q_TREE_ID__S_EQ;
            }
            this.loadData(this.queryParam);
        },
        search() {
            this.$refs.table.loadData();
        },
        cancel() {
            this.resetSearch();
        },
        closeSearchbar() {
            //关闭过滤弹窗；（点击X触发）
            this.fitSearch = false;
        },
        changeAppId(selectedRows){
            FormBoEntityApi.batchChangesApp(selectedRows);
        },
        //索引管理
        indexManager(record){
            var conf = {
                component: IndexComponent,
                curVm: this,
                widthHeight: ['800px', '600px'],
                title: this.i18n('list.indexManag','索引管理')+'-'+record.name,
                data: {
                    entityId:record.pkId,
                    tableName:record.tableName,
                    dsAlias:record.dsAlias,
                }
            }
            Util.open(conf, function (action, data) {});
        }
    }
}
</script>
<style scoped>

</style>

